package service.wx

import java.util.regex.Pattern

// 微信公众号普通消息的处理引擎
class WxMessager {
	// singleton
	private WxMessager(){}
	private static WxMessager inst = new WxMessager()
	public static WxMessager getInst(){
		return inst
	}

	private List<Handler> handlers = []
	private Closure noMatchHandler = null

	public void add(String msgType, String pat, Closure closure){
		for(one in handlers){
			// 如果存在，直接替换
			if(one.type == msgType && one.pat == pat){
				one.closure = closure 
				return
			}
		}
		handlers << new Handler(msgType, pat, closure)
	}

	public void noMatch(Closure closure){
		noMatchHandler = closure
	}

	// 主方法
	public Map<String, String> process(Map<String, String> info){
		for(one in handlers){
			if(one.type != info.MsgType)
				continue

			String key
			switch(info.MsgType){
			    case 'text':
					key = info.Content
			        break
			    case 'link':
					key = info.Url
			        break
			    case 'event':
					key = info.EventKey
			        break
			    default:
			        break
			}

			if(!key || key == one.pat || one.pattern.matcher(key).find())
				return one.closure.call(info)
		}

		if(noMatchHandler)
			return noMatchHandler.call(info)
		else 
			return null
	}

	private class Handler {
		String type
		String pat
		Pattern pattern

		Closure closure

		public Handler(String type, String pat, Closure closure){
			this.type = type
			this.pat = pat
			this.pattern = Pattern.compile(pat)
			this.closure = closure
		}
	}
}
